/**
 * 通用验证框架
 * 
 * @author zijing.zhang
 */
(function($ns) {

	/**
	 * 前后端约定的验证formId key 参考:
	 * com.qunar.common.admin.module.WebConstants.VALI_FORM_ID_KEY
	 */
	$ns.valiFormIdStr = "valiFormId";

	/**
	 * validator form
	 *  [ formId_1: { attr1: {}, attr2: {} ... }, formId_2: { attr1: {}, attr2: {} ... } ]
	 */
	$ns.valiForms = {};

	/**
	 * 绑定表单验证xml
	 */
	$ns.bindValiXml = function(xmlStr) {
		if (!xmlStr)
			return;

		var xml = Qadmin.FW.Xml, log = Qadmin.FW.Log, self = this;

		var dom = xml.loadXmlFromString(xmlStr);
		if (!dom) {
			log.debug("解析xml验证规则异常!");
			return;
		}

		var page = dom.getElementsByTagName("page")[0];

		var forms = page.getElementsByTagName("form");
		var j = 0;
		while (j < forms.length) {
			var formId = forms[j].getAttribute("id");
			self.valiForms[formId] = {};

			var propertyNodes = forms[j].childNodes;
			for ( var i = 0; i < propertyNodes.length; i++) {
				var attr = propertyNodes[i].getAttribute("name");
				var validator = {
					chname : propertyNodes[i].getAttribute("chname"),
					allowBlank : propertyNodes[i].getAttribute("allowBlank") === "false" ? false
							: true,
					minLen : parseInt(propertyNodes[i].getAttribute("minLen"),
							10),
					maxLen : parseInt(propertyNodes[i].getAttribute("maxLen"),
							10),
					regex : propertyNodes[i].getAttribute("regex"),
					regexJs : propertyNodes[i].getAttribute("regexJs"),
					prompt : propertyNodes[i].getAttribute("prompt")
				};

				self.valiForms[formId][attr] = validator;

				// 绑定表单属性验证
				self.bindFormAttr(formId, attr);
			}
			// alert(JSON.stringify(this.valiForms));

			// 绑定提交表单验证
			self.bindForm(formId);

			// 向form中增加hidden的formId参数
			self.addHiddenFormId(formId);

			j++;
		}
	};

	/**
	 * 向form中增加隐藏的formId便于后端辨识form拦截验证
	 * 
	 * @param formId
	 */
	$ns.addHiddenFormId = function(formId) {
		try {
			$('#' + formId).append(
					'<input type="hidden" name="' + this.valiFormIdStr
							+ '" value="' + formId + '" />');
		} catch (e) {
			log.error(e.message);
		}
	}

	/**
	 * 表单submit按钮触发验证, 整体验证表单
	 * 
	 * @param formId
	 */
	$ns.bindForm = function(formId) {
		var self = this;

		$('#' + formId + " input[type=submit]").bind("click", function() {
			var failValiAttrNum = 0;
			for ( var attr in self.valiForms[formId]) {
				if (self.match(formId, attr))
					failValiAttrNum++;
			}
			if (failValiAttrNum > 0)
				return false;
			return true;
		});
	}

	/**
	 * onkeyup事件触发表单属性验证
	 * 
	 * @param formId
	 * @param attr
	 *            属性id
	 */
	$ns.bindFormAttr = function(formId, attr) {
		var self = this;
		$('#' + formId + " #" + attr).bind("keyup change", function() {
			self.match(formId, attr);
		});
	};

	/**
	 * 根据规则校验事件
	 * 
	 * @param formId
	 * @param attr
	 *            用户输入的值
	 * @return boolean true - 匹配到未通过验证规则的属性
	 */
	$ns.match = function(formId, attr) {
		var self = this;

		if (!attr)
			return;
		// get validator
		var validator = self.valiForms[formId][attr];
		if (!validator)
			return;
		// log.debug("formId: "+ formId +", attr: "+ attr +", find validator: "
		// + JSON.stringify(validator));

		// tip msg
		var msg = "";

		// get attr value
		var value = $('#' + formId + ' #' + attr).val();
		if (Object.prototype.toString.apply(value) === '[object Array]') {
			value = value.join(",");
		}
		value = value == null ? "" : value.replace(/(^[\s]*)|([\s]*$)/g, "");

		// check blank
		if (!validator.allowBlank) {
			if (!value.length) {
				msg = validator.chname + "\u4e0d\u80fd\u4e3a\u7a7a!";
				self.tip(formId, attr, msg);
				return true;
			} else {
				self.tip(formId, attr);
			}
		}

		if (value != "") {
			// check minLen
			if (validator.minLen != -1) {
				if (getByteLen(value) < validator.minLen) {
					msg = validator.chname
							+ "\u957f\u5ea6\u4e0d\u80fd\u5c0f\u4e8e"
							+ validator.minLen;
					self.tip(formId, attr, msg);
					return true;
				} else {
					self.tip(formId, attr);
				}
			}

			// check maxLen
			if (validator.maxLen != -1) {
				if (getByteLen(value) > validator.maxLen) {
					msg = validator.chname
							+ "\u957f\u5ea6\u4e0d\u80fd\u5927\u4e8e"
							+ validator.maxLen;
					self.tip(formId, attr, msg);
					return true;
				} else {
					self.tip(formId, attr);
				}
			}

			// regexJs
			if (validator.regexJs) {
				var regex = new RegExp(validator.regexJs);
				if (!regex.test(value)) {
					var prompt = validator.prompt ? validator.prompt
							: "\u9a8c\u8bc1\u5931\u8d25";
					self.tip(formId, attr, prompt);
					return true;
				} else {
					self.tip(formId, attr);
				}
			}
		} else {
			// 移除提示
			self.tip(formId, attr);
		}

		function getByteLen(val) {
			// 暂不处理全角半角判断
			/*
			 * var len = 0; for (var i = 0; i < val.length; i++) { if
			 * (val[i].match(/[^\x00-\xff]/ig) != null) //全角 len += 2; else len +=
			 * 1; } return len;
			 */
			return val.length;
		}

	};

	/**
	 * 提示错误信息
	 * 
	 * @param formId
	 * @param attr
	 *            表单属性名
	 * @param prompt
	 *            错误提示信息
	 */
	$ns.tip = function(formId, attr, prompt) {
		var el = $('#' + formId + " #" + attr), error_class = "input_border_error";

		if (el.hasClass(error_class))
			el.removeClass(error_class);
		el.parent().find("span").remove();

		if (prompt) {
			prompt = '<span><img src="/resources/images/exclamation.gif" title="'
					+ prompt + '"/></span>';
			el.parent().append(prompt);
			el.addClass(error_class);
		}
	}

	/**
	 * 显示后台验证结果
	 * 
	 * @param result
	 */
	$ns.showServerValiResult = function(result) {
		if (!result)
			return;
		var msg = "";
		try {
			for ( var key in result.data) {
				if (result.data[key].length > 0) {
					msg += result.data[key][0] + "<br />";
				}
			}
			Qadmin.FW.Dialog.fail({
				msg : msg
			});
		} catch (e) {
			log.error(e.message);
		}
	}
})(using("Qadmin.FW.Validator"));